package com.xhy.documents_collection.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DeviceUtils {
    
    private static final Pattern[] OS_PATTERNS = {
        Pattern.compile("Windows NT ([\\d.]+)"),
        Pattern.compile("Mac OS X ([\\d_]+)"),
        Pattern.compile("Linux"),
        Pattern.compile("Android ([\\d.]+)"),
        Pattern.compile("(?:iPhone|iPad|iPod);.*(?:CPU iPhone)? OS ([\\d_]+)")
    };
    
    private static final String[] OS_NAMES = {
        "Windows",
        "Mac",
        "Linux",
        "Android",
        "iOS"
    };

    public static String getOs(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "Unknown";
        }
        for (int i = 0; i < OS_PATTERNS.length; i++) {
            Matcher matcher = OS_PATTERNS[i].matcher(userAgent);
            if (matcher.find()) {
                String version = (i == 4) ? matcher.group(1).replaceAll("_", ".") : matcher.group(1);
                return OS_NAMES[i] + " " + version;
            }
        }
        return "Unknown";
    }
}
